package com.guodi.model.utils;

import com.aspose.words.*;
import org.apache.commons.lang.StringUtils;

/**
 * @author 戴伙进
 * @time 2018/7/11 13:20
 * @function
 */
public class ReplaceImage implements IReplacingCallback {
    private String imageUrl;//图片地址
    private String qrcodeContent;//二维码内容
    private double width;
    private double height;
    private String alignment;//grid为表格中插入图片，将图片居中，其他不进行居中

    public ReplaceImage(String url, String qrcodeContent, double width, double height, String alignment) {
        this.imageUrl = url;
        this.qrcodeContent = qrcodeContent;
        this.width = width;
        this.height = height;
        this.alignment = alignment;
    }

    @Override
    public int replacing(ReplacingArgs args) throws Exception {
        if (!StringUtils.isEmpty(imageUrl)) {
            Node node = args.getMatchNode();
            DocumentBuilder builder = new DocumentBuilder((Document) node.getDocument());
            builder.moveTo(node);
            if (alignment != null && "grid".equalsIgnoreCase(alignment)) {
                Shape shape = builder.insertImage(imageUrl, 1, 8, 1, 8, width, height, WrapType.TOP_BOTTOM);
                shape.setHorizontalAlignment(HorizontalAlignment.CENTER);
            } else {
                builder.insertImage(imageUrl, width, height);
            }
            return 0;
        } else if (!StringUtils.isEmpty(qrcodeContent)) {
            Node node = args.getMatchNode();
            DocumentBuilder builder = new DocumentBuilder((Document) node.getDocument());
            builder.moveTo(node);
            if (alignment != null && "grid".equalsIgnoreCase(alignment)) {
                Shape shape = builder.insertImage(QRCodeUtil.createQrCode(qrcodeContent, 600, 600), 1, 8, 1, 8, width, height, WrapType.TOP_BOTTOM);
                shape.setHorizontalAlignment(HorizontalAlignment.CENTER);
            } else {
                builder.insertImage(QRCodeUtil.createQrCode(qrcodeContent, 600, 600), width, height);
            }
            return 0;
        } else {
            return 1;
        }
    }
}
